package com.android.kotlincoroutinemvvmdemo.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.util.Log
import com.android.kotlincoroutinemvvmdemo.R

class SurfaceView01 @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : SurfaceViewTemplate(context, attributeSet) {

    private val mPaint0 by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            strokeCap = Paint.Cap.ROUND
            style = Paint.Style.STROKE
            color = context.resources.getColor(R.color.color_BF2F0B)
        }
    }

    private val mPaint1 by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            color = context.resources.getColor(R.color.color_BF2F0B)
        }
    }

    private val textBound by lazy {
        Rect()
    }

    private var textContent = "5G"

    init {
        mHolder.addCallback(this)
    }

    override fun Canvas.onDrawContent() {
        val cx = mWidth.toFloat()
        val cy = mHeight.toFloat()

        drawColor(context.resources.getColor(R.color.color_F3F3F3))
        val mStrokeWidth = (cx * 1 / 20).coerceAtLeast(minStrokeWidth)
        mPaint0.strokeWidth = mStrokeWidth

        for (i in 0.until(PIECES)) {
            drawLine(
                cx * (PIECES - i) / PIECES - mStrokeWidth / 2,
                cy * i / PIECES + mStrokeWidth / 2,
                cx * (PIECES - i) / PIECES - mStrokeWidth / 2,
                cy - mStrokeWidth / 2,
                mPaint0
            )
        }

        mPaint1.getTextBounds(textContent, 0, textContent.length, textBound)
        val mTextSize = cx * 1 / 4
        mPaint1.textSize = mTextSize
        drawText(
            textContent,
            0F,
            textBound.height().toFloat(),
            mPaint1
        )
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        Log.d(TAG,"${TAG}---override fun onMeasure")
    }

    fun setContent(textContent: String) {
        this.textContent = textContent
        invalidate()
    }

    companion object {
        const val TAG = "SurfaceView01"

        const val PIECES = 5
    }
}